<template>
  <a-layout>
    <!-- 顶部导航栏 -->
    <a-layout-header class="app-header">
      <div class="header-container">
        <!-- 左侧品牌区 -->
        <div class="brand-section">
          <div class="logo" @click="handleLogoClick">
            <img src="./static/logo.svg" alt="Logo" />
            <span class="brand-name">Simply Rubby</span>
          </div>
        </div>

        <!-- 中央菜单区 -->
        <div class="menu-section">
          <a-menu v-model:selectedKeys="activeIndex" mode="horizontal" :items="leftMenuItems" class="nav-menu"
            @click="handleSelect" />
        </div>

        <!-- 右侧用户区 -->
        <div v-if="authStore.isAuthenticated" class="user-section">
          <a-dropdown :trigger="['hover']">
            <a-avatar :size="36" style="background-color: #1890ff">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
            <template #overlay>
              <a-menu :items="userDropdownItems" @click="handleDropdownSelect" />
            </template>
          </a-dropdown>
        </div>
      </div>
    </a-layout-header>

    <!-- 面包屑导航 -->
    <div class="breadcrumb-bar">
      <!-- 修改后的面包屑导航 -->
      <a-breadcrumb class="breadcrumb">
        <a-breadcrumb-item v-for="item in breadcrumbItems" :key="item.name" :to="item.to">
          <router-link :to="item.to"> <!-- 添加路由链接 -->
            <span class="breadcrumb-item-container">
              <span class="breadcrumb-icon-wrapper">
                <component :is="getIconComponent(item.icon)" />
              </span>
              <span class="breadcrumb-text">{{ item.text }}</span>
            </span>
          </router-link>
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-layout-content class="app-main">
      <router-view></router-view>
    </a-layout-content>
  </a-layout>
</template>


<script setup lang="ts">
import { ref, watch, computed, h } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useAuthStore } from './store/auth';
import { HomeOutlined, FileTextOutlined, EditOutlined, ProfileOutlined, UserAddOutlined, LogoutOutlined, UserOutlined, EyeOutlined } from '@ant-design/icons-vue';
import { notification } from 'ant-design-vue'; // 引入 notification

interface MenuItem {
  key: string;
  label: string;
  icon?: any; // 添加 icon 属性
  children?: MenuItem[]; // 添加 children 属性
}
// 定义路由元信息的类型
interface RouteMeta {
  breadcrumb: string; // 明确指定 breadcrumb 为 string 类型
  parent?: string;    // 父路由名称
}
// 在 App.vue 的 script setup 中
const iconMap = {
  home: HomeOutlined,
  news: FileTextOutlined,
  create: EditOutlined,
  application: UserAddOutlined,
  user: UserOutlined,
  match: ProfileOutlined,
  detail: EyeOutlined, // 假设需要详情图标
  login: UserOutlined,
};

const getIconComponent = (iconName: string) => {
  return iconMap[iconName]
};
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const activeIndex = ref<string[]>([route.name?.toString() || 'home']);

// 左侧菜单项
const leftMenuItems = computed(() => {
  const items: MenuItem[] = [
    {
      key: 'home',
      label: '首页',
      icon: () => h(HomeOutlined, { style: { color: '#1890ff' } }) // 首页图标
    },
  ];
  items.push({
    key: 'news',
    label: '公告',
    icon: () => h(FileTextOutlined, 1.-{ style: { color: '#1890ff' } }),
    children: [
      {
        key: 'News',
        label: '公告列表',
        icon: () => h(FileTextOutlined, { style: { color: '#1890ff' } })
      },
      ...(authStore.isAuthenticated && (authStore.isAdmin || authStore.isCoach) ? [ // 权限判断
        {
          key: 'CreateNews',
          label: '创建公告',
          icon: () => h(EditOutlined, { style: { color: '#1890ff' } })
        }
      ] : [])
    ]
  });
  items.push({
    key: 'MatchRecord',
    label: '比赛记录',
    icon: () => h(ProfileOutlined, { style: { color: '#1890ff' } }) // 比赛记录图标
  })
  if (!authStore.isAuthenticated) {
    items.push({
      key: 'application',
      label: '申请相关',
      icon: () => h(UserAddOutlined, { style: { color: '#1890ff' } }), // 申请相关图标
      children: [
        {
          key: 'NonMemberApplication',
          label: '申请非玩家会员',
          icon: () => h(UserAddOutlined, { style: { color: '#1890ff' } }) // 子菜单图标
        },
        {
          key: 'MemberApplication',
          label: '申请玩家会员',
          icon: () => h(UserAddOutlined, { style: { color: '#1890ff' } }) // 子菜单图标
        },
      ],
    });

  }


  if (authStore.isAuthenticated) {
    if (!authStore.isGuest) {
      items.push();
    }
    if (!authStore.isCoach) {
      items.push({
        key: 'application',
        label: '申请相关',
        icon: () => h(UserAddOutlined, { style: { color: '#1890ff' } }), // 申请相关图标
        children: [
          {
            key: 'NonMemberApplication',
            label: '申请非玩家会员',
            icon: () => h(UserAddOutlined, { style: { color: '#1890ff' } }) // 子菜单图标
          },
          {
            key: 'MemberApplication',
            label: '申请玩家会员',
            icon: () => h(UserAddOutlined, { style: { color: '#1890ff' } }) // 子菜单图标
          },
        ],
      });
    }
  } else {
    items.push({
      key: 'auth',
      label: '登录',
      icon: () => h(UserOutlined, { style: { color: '#1890ff' } }) // 登录图标
    });
  }

  if (authStore.isAuthenticated && (authStore.isAdmin || authStore.isCoach)) {
    items.push({
      key: 'memberManagement',
      label: '会员管理',
      icon: () => h(UserAddOutlined, { style: { color: '#1890ff' } }), // 申请相关图标
      children: [
        {
          key: 'AdultMemberManagement',
          label: '成年会员管理',
          icon: () => h(UserOutlined, { style: { color: '#1890ff' } }) // 会员管理图标
        },
        {
          key: 'MinorMemberManagement',
          label: '未成年会员管理',
          icon: () => h(UserOutlined, { style: { color: '#1890ff' } }) // 会员管理图标
        }
      ]
    });
  }

  return items;
});


// 用户下拉菜单项
const userDropdownItems = computed(() => {
  const items: MenuItem[] = [];

  if (authStore.isAuthenticated) {
    items.push(
      {
        key: 'userProfile',
        label: '用户主页',
        icon: () => h(UserOutlined, { style: { color: '#1890ff' } }) // 添加用户主页图标
      },
      {
        key: 'logout',
        label: '退出登录',
        icon: () => h(LogoutOutlined, { style: { color: '#ff4d4f' } }) // 保留退出登录图标
      }
    );
  }

  return items;
});



const breadcrumbItems = computed(() => {
  const getBreadcrumbByRouteName = (name: string | undefined): { name: string; text: string; to: any }[] => {
    if (!name) return [];

    // 使用 router.getRoutes() 获取所有路由记录
    const routeRecord = router.getRoutes().find((r) => r.name === name);
    if (!routeRecord) return [];

    // 确保 meta 存在且 breadcrumb 为 string 类型
    const breadcrumb = (routeRecord.meta?.breadcrumb as string) || '未知';
    const parentName = routeRecord.meta?.parent;

    // 确保 parentName 是字符串类型
    const parentBreadcrumbs = typeof parentName === 'string'
      ? getBreadcrumbByRouteName(parentName)
      : [];

    return [
      ...parentBreadcrumbs,
      {
        name: routeRecord.name as string,
        text: breadcrumb,
        to: routeRecord.path,  // 使用 path 更可靠
        icon: routeRecord.meta?.icon
      },
    ];
  };

  const currentRouteBreadcrumbs = getBreadcrumbByRouteName(route.name?.toString());

  // 如果没有首页，则手动添加首页
  if (!currentRouteBreadcrumbs[0]?.text.includes('首页')) {
    currentRouteBreadcrumbs.unshift({
      name: 'Home',
      text: '首页',
      to: { name: 'Home' }, // 确保首页路由有效
    });
  }

  return currentRouteBreadcrumbs;
});

watch(route, (newRoute) => {
  activeIndex.value = [newRoute.name?.toString() || 'home'];
});

const handleSelect = ({ key }: { key: string }) => {
  router.push({ name: key.charAt(0).toUpperCase() + key.slice(1) });
};

const handleDropdownSelect = ({ key }: { key: string }) => {
  if (key === 'logout') {
    showLogoutNotification(); // 显示退出登录通知
    authStore.logout();
    router.push({ name: 'Home' });
  } else if (key === 'userProfile') {
    router.push({ name: 'UserProfile' });
  }
};

const handleLogoClick = () => {
  router.push({ name: 'Home' });
};

// 显示退出登录通知
const showLogoutNotification = () => {
  notification.success({
    message: '退出登录成功',
    description: '您已成功退出登录账号。',
    duration: 3, // 持续时间（秒）
    placement: 'topRight', // 通知位置
  });
};
</script>

<style scoped>
/* 顶部导航栏样式 */
.app-header {
  height: 56px;
  line-height: 56px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0 24px;
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1000;

}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.brand-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo img {
  height: 32px;
}

.brand-name {
  font-size: 18px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
}

.menu-section {
  flex: 1;
  margin: 0 40px;
}

.nav-menu {
  line-height: 56px;
  border-bottom: none;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 面包屑样式 */
.breadcrumb-bar {
  height: 48px;
  /* 固定高度 */
  padding: 12px 24px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: fixed;
  top: 56px;
  width: 100%;
  z-index: 999;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: flex-start;
  /* 主轴左对齐 */

}

.breadcrumb-item-container {
  cursor: pointer;
  transition: color 0.3s;

  &:hover {
    color: #1890ff;
  }
}

/* 图标圆框样式补充 */
.breadcrumb-icon-wrapper {
  margin-right: 8px;
}

.breadcrumb {
  max-width: 1200px;
  margin: 0;
}

.breadcrumb-text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

.ant-breadcrumb-separator {
  margin: 0 8px;
}

.ant-breadcrumb a {
  text-decoration: none;
}

/* 主要内容区域 */
.app-main {
  margin-top: 104px;
  /* 导航栏56px + 面包屑48px */
  padding: 24px;
  min-height: calc(100vh - 104px - 24px);
  /* 减去自身 padding-bottom */
  background: #f0f2f5;
}
</style>